<?php
function bend_op(&$retparams){
	global $_db;
	
	if(!isset($_POST['op'])){
		return BEND_REDIRECT;
	}
	elseif("addview"==$_POST['op']){
		echo rendertpl("applet/opaddmod.applet");
		return BEND_RENDERED;
	}
	elseif("add"==$_POST['op']){
		$id = $_db->insert("op", array("viewname"=>$_POST['viewname'], 
			"opname"=>$_POST['opname'], "desc"=>$_POST['desc'], "title"=>$_POST['title']));
		if($id>0){
			$retparams['errorcode'] = 0;
		}
		else{
			$retparams['errorcode'] = -1;
		}
		return BEND_ECHORET;
	}
	elseif("del"==$_POST['op']){
		$count = $_db->delete("op", "id=$_POST[id]");
	}
	elseif("modview"==$_POST['op']){
		echo rendertpl("applet/opaddmod.applet");
		return BEND_RENDERED;
	}
	elseif("mod"==$_POST['op']){
		$count = $_db->update("op"
			,array("viewname"=>$_POST['viewname'] 
				,"opname"=>$_POST['opname'], "desc"=>$_POST['desc'],"title"=>$_POST['title'])
			,"id=$_POST[id]");
		if($count>0){
			$retparams['errorcode'] = 0;
		}
		else{
			$retparams['errorcode'] = -1;
		}
		return BEND_ECHORET;
	}
	elseif("search"==$_POST['op']){
		return BEND_HOMEPAGE;
	}
	elseif("autoupdateop"==$_POST['op']){
		//$_db->delete("op", null, true);
		$params = array();
		
		$benddirstr = ROOT_DIR."/bend/";
		$benddir = opendir($benddirstr);
		while(false!==($bendfile=readdir($benddir))){
			preg_match('/bend\.(\w+)\.php/i', $bendfile, $match);
			$viewname = $match[1];
			
			$content = readfromfile($benddirstr.$bendfile);
			preg_match_all('/if\s*\(\"(\w+)\"\s*==\s*\$_POST\[\'op\'\]\s*\)/', $content, $matches);
			foreach($matches[1] as $op){
				$params["viewname"] = $viewname;
				$params["opname"] = $op;
				if(isempty(getop($params)))
					$_db->insert("op", array("viewname"=>$viewname, "opname"=>$op));
				//TODO 失效不存在的op
			}
		}
	}
	return BEND_REDIRECT;
}
?>